/*
 * @Author: your name
 * @Date: 2021-11-10 08:34:30
 * @LastEditTime: 2021-12-17 13:44:26
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \li-yuwei\egg-example\app\service\login.js
 */

const Service = require("egg").Service;
const timeFormart = require("../extends/timeFormart");
class InformationService extends Service {
    //获取列表
    async getInformationList() {
            const { ctx, app } = this;
            let res = await app.mysql.select("information");
            res = res.sort((a, b) => {
                return new Date(b.create_time) - new Date(a.create_time);
            });
            res = res.map((item, index) => {
                return {
                    ...item,
                    key: index + 1,
                };
            });
            return res;
        }
        //搜索
    async searchInformationList() {
            const { ctx, app } = this;
            const { keyword, state } = ctx.query;
            let res = await app.mysql.select("information");
            if (keyword) {
                res = res.filter((item) => item.title.includes(keyword));
            }
            if (state !== undefined) {
                res = res.filter((item) => item.state * 1 === state * 1);
            }
            res = res.map((item, index) => {
                return {
                    ...item,
                    key: index + 1,
                };
            });
            return res;
        }
        //删除
    async delInformationList() {
            const { ctx, app } = this;
            const { id } = ctx.params;
            const res = await app.mysql.delete("information", { id });
            return res;
        }
        //改变状态
    async changeInformationState() {
        const { ctx, app } = this;
        const { id } = ctx.params;
        const res = await app.mysql.get("information", { id });
        const state = res.state * 1;
        const result = await app.mysql.update("information", {
            id,
            state: !state,
        });
        return result;
    }

    //编辑
    async editInformationList() {
            const { ctx, app } = this;
            const { id, title, state } = ctx.request.body;
            if (state !== undefined && title !== undefined) {
                const res = await app.mysql.update("information", { id, state, title });
                return res;
            } else {
                return 417;
            }
        }
        //新增
    async addInformationList() {
        const { ctx, app } = this;
        const { title, state, creator } = ctx.request.body;
        const res = await app.mysql.insert("information", {...ctx.request.body, create_time: timeFormart(Date.now()) });
        return res;
    }
}
module.exports = InformationService;